<?php
declare(strict_types=1);
namespace cms\wechat\api_controller;

use cms\wechat\service\AuthorizeService;
use cms\wechat\service\OfficialService;
use cms\wechat\service\PlatformService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Psr\Http\Message\ResponseInterface;

/**
 * Class PlatformController
 * @package cms\wechat\api_controller
 * @Controller(prefix="api/wechat/platform")
 */
class PlatformController extends CommonController
{
    /**
     * @Inject()
     * @var PlatformService
     */
    protected PlatformService $platformService;

    /**
     * @Inject()
     * @var OfficialService
     */
    protected OfficialService $officialService;

    /**
     * @Inject()
     * @var AuthorizeService
     */
    protected AuthorizeService $authorizeService;

    /**
     * @return ResponseInterface
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @GetMapping(path="authorize")
     */
    public function authorize(): ResponseInterface
    {
        $id = (int) $this->request->input('id', 0);
        $platform = $this->platformService->getDataById($id, true);
        // 实例化开放平台
        $platform_application = $this->platformService->initApplication($platform);
        // 开放平台授权码
        $auth_code = $this->request->input('auth_code', '');
        if ($auth_code) {
            // 使用授权码换取接口调用凭据和授权信息
            $auth_data = $platform_application->handleAuthorize($auth_code);
            // 获取授权方的帐号基本信息
            $auth_info = $platform_application->getAuthorizer($auth_data['authorization_info']['authorizer_appid']);
            // var_dump($auth_info);
            // 获取授权方的选项设置信息
            // $auth_option = $platform_application->getAuthorizerOption();
            // 设置授权方的选项信息
            // $auth_option_set = $platform_application->setAuthorizerOption();
            // 获取已授权的授权方列表
            // $auth_list = $platform_application->getAuthorizers();
            // 同步账号信息
            $official = $this->officialService->syncDataByAuth($auth_info);
            if (! $official) {
                return $this->error('授权失败');
            }
            //更新授权信息
            $this->authorizeService->syncDataByAuth($platform, $auth_info);
            return $this->success('授权成功');
        }
        $callback = $this->request->fullUrl();
        $redirect = $platform_application->getPreAuthorizationUrl($callback);
        return $this->success('请求成功', [
            'redirect' => $redirect
        ]);
    }
}